package cn.ming.leo.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.client.ClientProtocolException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.PagedList;

import cn.ming.leo.bean.DoorTools;
import cn.ming.leo.bean.User;
import cn.ming.leo.bean.WechatInfo;
import cn.ming.leo.bean.vo.TemplateData;
import cn.ming.leo.bean.vo.TemplateMsgRequest;
import cn.ming.leo.utils.Constant.MsgCode;
import cn.ming.leo.utils.HttpClientUtil;
import cn.ming.leo.utils.Message;
import cn.ming.leo.utils.PageListModel;
import cn.ming.leo.utils.TimeFormat;
import cn.ming.leo.bean.SysCode;

@Service
public class UserService {

	public Message<String> remove(int id) {
		User w = User.find.byId(String.valueOf(id));
		w.delete();
		return new Message<String>("ok");
	}

	public Message<Map<String, Object>> view(int id) {
		Map<String, Object> map = new HashMap<>();

		User user = User.find.byId(String.valueOf(id));
		WechatInfo wechatInfo = WechatInfo.find.where().eq("open_id", user.getOpenId()).findUnique();
		user.setWechatInfo(wechatInfo);
		map.put("user", user);
		map.put("records", DoorTools.find.where().eq("put_user_id", id).findList());

		return new Message<Map<String, Object>>(map);
	}

	public Message<String> regist(String mobile, String code, String openId) {
		SysCode sysCode = SysCode.find.where().eq("mobile", mobile).eq("code", code).findUnique();
		if (sysCode == null) {
			return new Message<String>(MsgCode.FAIL.value, "验证码错误");
		}
		sysCode.delete();

		User user1 = User.find.where().eq("mobile", mobile).findUnique();

		if (user1 != null) {
			return new Message<String>(MsgCode.FAIL.value, "手机号已被注册");
		}

		User user = new User();
		user.setCreateTime(TimeFormat.nowTime());
		user.setMobile(mobile);
		user.setOpenId(openId);
		user.insert();
		user.refresh();

		return new Message<String>(String.valueOf(user.getId()));
	}

	public Message<String> updateStatus(int id, int status) {
		User box = User.find.byId("" + id);
		box.setStatus(status);
		box.update();
		return new Message<String>("success");
	}

	public Message<String> updateFlag(String mobile) {
		User box = User.find.where().eq("mobile", mobile).findUnique();
		if (box == null) {
			return new Message<String>(MsgCode.FAIL.value, "手机号不存在");

		}
		box.setFlag(3);
		box.update();
		return new Message<String>("success");
	}

	public Message<String> updateRoles(int id, int roles) {
		User box = User.find.byId("" + id);
		box.setRoles(roles);
		box.update();
		return new Message<String>("success");
	}

	public Message<PageListModel<User>> findAll(Integer pageIndex, Integer pageSize) {
		PagedList<User> pl;
		ExpressionList<User> pression = Ebean.find(User.class).where();

		pageIndex = (pageIndex == null) ? 0 : pageIndex - 1;
		pageSize = (pageSize == null) ? 10 : pageSize;

		pl = pression.eq("flag", 0).order().desc("create_time").findPagedList(pageIndex, pageSize);

		PageListModel<User> pageListModel = new PageListModel<User>(pl);
		for (User user : pageListModel.getList()) {
			WechatInfo wechatInfo = WechatInfo.find.where().eq("open_id", user.getOpenId()).findUnique();
			user.setWechatInfo(wechatInfo);
		}
		return new Message<PageListModel<User>>(pageListModel);
	}

	public Message<PageListModel<User>> findAll1(Integer pageIndex, Integer pageSize) {
		PagedList<User> pl;
		ExpressionList<User> pression = Ebean.find(User.class).where();

		pageIndex = (pageIndex == null) ? 0 : pageIndex - 1;
		pageSize = (pageSize == null) ? 10 : pageSize;

		pl = pression.ge("flag", 2).order().desc("create_time").findPagedList(pageIndex, pageSize);

		PageListModel<User> pageListModel = new PageListModel<User>(pl);
		for (User user : pageListModel.getList()) {
			WechatInfo wechatInfo = WechatInfo.find.where().eq("open_id", user.getOpenId()).findUnique();
			user.setWechatInfo(wechatInfo);
		}
		return new Message<PageListModel<User>>(pageListModel);
	}

	public Message<String> transferRole(Integer userId, String mobile) {
		User u = User.find.where().eq("mobile", mobile).findUnique();
		if (u == null) {
			return new Message<String>(MsgCode.FAIL.value, "手机号不存在");

		}
		u.setFlag(3);
		u.update();

		User box = User.find.where().eq("mobile", mobile).findUnique();
		box.setFlag(0);
		box.update();

		return new Message<String>("success");
	}

	public void sendWechatMsg() throws ClientProtocolException, IOException {
		TemplateMsgRequest req = new TemplateMsgRequest();

		req.setTemplate_id("5tPSztJYXTDtdzg6dhVaEKOWB6W85gCa3vf1VeJEqnU");
		req.setTouser("o_YfoskQYzatPc_UJc1zg4GdI16s");
		req.setUrl("url");
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = sdf.format(now);
		Map<String, TemplateData> data = new TreeMap<String, TemplateData>();
		data.put("first", new TemplateData("你的任务已完成", "#173177"));
		data.put("keyword1", new TemplateData("keyword", "#173177"));
		data.put("keyword2", new TemplateData(str, "#173177"));
		data.put("keyword3", new TemplateData(1 + "童币", "#173177"));
		data.put("remark", new TemplateData("此项任务的奖励已存入你的球童账户内，点击【详情】立刻进入大转盘抽奖吧！", "#173177"));
		req.setData(data);
		sendModuleMsg(JSONObject.toJSONString(req));
	}

	public static boolean sendModuleMsg(String reqStr) throws ClientProtocolException, IOException {
		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken();
		String jsonStr = HttpClientUtil.post(url, reqStr);
		JSONObject jo = JSON.parseObject(jsonStr);
		if (jo.getIntValue("errcode") == 0) {
			return true;
		} else {
			return false;
		}
	}

	public static String getAccessToken() throws ClientProtocolException, IOException {
		String appid = "appid";
		String secrect = "sercee";
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret="
				+ secrect;
		String jsonStr = HttpClientUtil.post(url, "");
		JSONObject jo = JSON.parseObject(jsonStr);
		return jo.get("access_token").toString();
	}
}
